package com.wonyesoft.wuliu.acticity;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.CaptureActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.wonyesoft.wuliu.AppContent;
import com.wonyesoft.wuliu.R;
import com.wonyesoft.wuliu.acticity.base.BaseActivity;
import com.wonyesoft.wuliu.acticity.utils.UpdateManager;
import com.wonyesoft.wuliu.api.GagApi;
import com.wonyesoft.wuliu.vo.JsonRequest;
import com.wonyesoft.wuliu.vo.JsonResponse;
import com.wonyesoft.wuliu.vo.State;


public class MainActivityActivity extends BaseActivity implements
		OnClickListener, OnCheckedChangeListener {

	private TabHost mTabHost;
	private RadioGroup mRadioGroup;
	
	private RequestParams params;

	public static Gson gson = new Gson();

	private HttpUtils http = new HttpUtils();

	private AppContent app;

	private PreferencesCookieStore preferencesCookieStore;

	private SharedPreferences share;

	private String key = "UserInfo";

	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity); 
		app = (AppContent) getApplication();
		preferencesCookieStore = app.getPreferencesCookieStore();
		mTabHost = (TabHost) findViewById(R.id.mainTableHost);
		mRadioGroup = (RadioGroup) findViewById(R.id.radiogroup);
		// mTabHost.setup(getLocalActivityManager());
		initRadioGroup();
		addTabIntent();
		isLogin();
		mTabHost.setCurrentTabByTag("index_tab");
		try {
			checkVersion();
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void initRadioGroup() {
		((RadioButton) findViewById(R.id.radio_choumeibang))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.radio_hairscan))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.radio_discover))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.radio_me))
				.setOnCheckedChangeListener(this);

	}

	// 绑定点击按钮
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.chadan:
			startActivityForResult(new Intent(this, CaptureActivity.class), 0);
			break;

		default:
			break;
		}
	}
	// 切换模块
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			switch (buttonView.getId()) {
			case R.id.radio_choumeibang:
				this.mTabHost.setCurrentTabByTag("index_tab");
				break;
			case R.id.radio_hairscan:
				this.mTabHost.setCurrentTabByTag("message_tab");
				break;
			case R.id.radio_discover:
				//this.mTabHost.setCurrentTabByTag("userinfo_tab");
				openActivity(OrderListsActivity.class);
				break;
			case R.id.radio_me:
				this.mTabHost.setCurrentTabByTag("setting_tab");
				break;
			}
		}
	}

	// 绑定切换Activity
	private void addTabIntent() {
		mTabHost.setup(getLocalActivityManager());
		this.mTabHost.addTab(buildTabSpec("index_tab", "index_tab", new Intent(this,
				TestAcivity.class)));
		/*this.mTabHost.addTab(buildTabSpec("message_tab", "message_tab", new Intent(
				this, UserCenterActivity.class)));
		this.mTabHost.addTab(buildTabSpec("userinfo_tab", "userinfo_tab", new Intent(
				this, UserOwnListActivity.class)));*/
		this.mTabHost.addTab(buildTabSpec("setting_tab", "setting_tab", new Intent(
				this, SettingActivity.class)));
	}

	private void isLogin() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		JsonRequest jr = JsonRequest.getInit();
		jr.setData(dataMap);
		String json = gson.toJson(jr);
		params = new RequestParams();
		params.addBodyParameter("jsonParam", json);
		http.configCookieStore(preferencesCookieStore);
		http.send(HttpRequest.HttpMethod.POST, GagApi.ISLOGIN, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						Gson gson2 = new Gson();
						JsonResponse jrs = gson2.fromJson(responseInfo.result,
								JsonResponse.class);
						System.out.println(responseInfo.result);
						State state = jrs.getState();
						// System.out.println(preferencesCookieStore);
						if (state.getCode().equals(State.SUCEECCODE)) {
							// 存用户登录信息
							System.out.println("登录啦！");
							MainActivityActivity.this.mTabHost.addTab(buildTabSpec("message_tab", "message_tab", new Intent(
									MainActivityActivity.this, UserCenterActivity.class)));
							MainActivityActivity.this.mTabHost.addTab(buildTabSpec("userinfo_tab", "userinfo_tab", new Intent(
									MainActivityActivity.this, OrderListsActivity.class)));
						} else
							// System.out.println(state.getMsg());
							{
							System.out.println("没有登录啦！");
							//cc = UserLoginActivity.class;
							MainActivityActivity.this.mTabHost.addTab(buildTabSpec("message_tab", "message_tab", new Intent(
									MainActivityActivity.this, UserLoginActivity.class)));
							MainActivityActivity.this.mTabHost.addTab(buildTabSpec("userinfo_tab", "userinfo_tab", new Intent(
									MainActivityActivity.this, UserLoginActivity.class)));
							}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// testTextView.setText(error.getExceptionCode() + ":" +
						System.out.println("网络都求没得啦！");
						MainActivityActivity.this.mTabHost.addTab(buildTabSpec("message_tab", "message_tab", new Intent(
								MainActivityActivity.this, UserLoginActivity.class)));
						MainActivityActivity.this.mTabHost.addTab(buildTabSpec("userinfo_tab", "userinfo_tab", new Intent(
								MainActivityActivity.this, UserLoginActivity.class)));
						System.out.println(msg);
						Toast.makeText(MainActivityActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
						//return(UserLoginActivity.class);
					}
				});
	}

	private TabHost.TabSpec buildTabSpec(String tag, String m,
			final Intent content) {
		return this.mTabHost.newTabSpec(tag).setIndicator(m)
				.setContent(content);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == 0) {
			String result = data.getExtras().getString("result");
			if (TextUtils.isEmpty(result)) {
				Toast.makeText(this, "uucc", Toast.LENGTH_LONG).show();
				return;
			}

			// s.setText(result);

		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	private void checkVersion() throws NameNotFoundException {
		// 检查版本更新

		int verCode = this.getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
			System.out.println("版本号：" + verCode);

			Map<String, Object> dataMap = new HashMap<String, Object>();
			JsonRequest jr = JsonRequest.getInit();
			dataMap.put("versionNumber", verCode + "");
			dataMap.put("versionType", "用户版本");
			jr.setData(dataMap);
			String json = gson.toJson(jr);
			System.out.println(json);
			http = new HttpUtils();
			params = new RequestParams();
			params.addBodyParameter("jsonParam", json);
			http.send(HttpRequest.HttpMethod.POST, GagApi.CheckVersion, params,
					new RequestCallBack<String>() {

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							// testTextView.setText("reply: " +
							// responseInfo.result);
							JsonResponse jrs = gson.fromJson(responseInfo.result,
									JsonResponse.class);
							System.out.println("升级 + " + responseInfo.result);
							State state = jrs.getState();
							if (state.getCode().equals(State.SUCEECCODE)) {
								if (GagApi.UPAPKPATH != null) {
									UpdateManager uManager = new UpdateManager(
											MainActivityActivity.this);
									uManager.apkUrl = GagApi.UPAPKPATH;
									uManager.checkUpdateInfo();
								}else {
									System.out.println("已经是最新的版本");
									//
								}
								// findXq();

							} else
								System.out.println(state.getMsg());
								//ToastUtils.showLong(state.getMsg());
						}

						public void onFailure(HttpException error, String msg) {
							System.out.println(msg);
						}
					});

		}		


}
